package com.study.manage.mvc.org.charge;

import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.EvaluatePriceRepository;
import com.study.manage.dal.OrderRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.EvaluateApply;
import com.study.manage.domain.EvaluatePrice;
import com.study.manage.domain.Order;
import com.study.manage.domain.User;
import com.study.manage.domain.enumm.EvaluateApplyVerifyState;
import com.study.manage.domain.enumm.OrderState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.mvc.common.CommonService;
import com.study.manage.utils.CmnDateUtil;
import com.study.manage.utils.MapUtils;

@Controller
@RequestMapping("org/evaluate/detail/caiwu")
public class EvaluateCaiwuController extends BaseController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EvaluatePriceRepository evaluatePriceRepository;
    @Autowired
    private EvaluateApplyRepository evaluateApplyRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CommonService commonService;
    
    @RequestMapping(path = "info", method = RequestMethod.GET)
    public String info() {
        return "org/evaluate/caiwu";
    }

    @ResponseBody
    @RequestMapping(path = "getTableData", method = RequestMethod.GET)
    public AjaxResponse info_list(Date date, Long evaluateId,Integer  flg,
    		@DateTimeFormat(pattern = "yyyy-MM-dd") Date beginAt,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endAt,
            String name, EvaluateApplyVerifyState verifyState, OrderState orderState,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {
    	
        AjaxResponse ajax = new AjaxResponse(true);
        List<Long> evaluateIds = new ArrayList<>(Arrays.asList(evaluateId));
        Map<String,Date> timeMap = commonService.getTimes(beginAt,endAt,evaluateIds,flg);
        beginAt = timeMap.get("beginAt");
        endAt = timeMap.get("endAt");
        session.setAttribute("beginAt",beginAt);
        session.setAttribute("endAt",endAt);
        Page<Order> page = orderRepository.findByEvaluateIdAndDateAndName(evaluateId,name,orderState, pageable,beginAt,endAt);
        Object obj = page.map(new Converter<Order, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Order source) {
                EvaluateApply ea = evaluateApplyRepository.findByEvaluateIdAndUserId(source.itemId,source.userId);
                if(ea==null ) {
                	ea = new EvaluateApply();
                };
                Map<String, Object> map = MapUtils.convert(ea);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("userPhone", user.phone);
                map.put("orderItemTypeDesc", source.itemType.desc);
                map.put("orderStateDesc", source.state.desc);
                map.put("orderTradeTypeDesc",source.tradeType == null ? "" : source.tradeType.desc);
                map.put("orderCreatedAt", source.createdAt);
                if(OrderState.UNPAID==source.state){
                	map.put("orderItemPrice", "0.00");
                }else{
                	map.put("orderItemPrice", source.itemPrice);
                }
                map.put("orderId", source.id);
                if (ea.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(ea.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                }
                if (ea.referenceId != null) {
                    User refUer = userRepository.findOne(ea.referenceId);
                    map.put("refName", refUer.name);
                }
                return map;
            }
        });
        return ajax.setObj(obj);
    }


    @ResponseBody
    @RequestMapping(path = "info-detail-count", method = RequestMethod.GET)
    public AjaxResponse list_detail_count(HttpServletRequest request, Long evaluateId) {
    	
        AjaxResponse ajax = new AjaxResponse(true);
        Date date = new Date();
        List<Long> es = new ArrayList<>(Arrays.asList(evaluateId));
        Map<String, Object> map = new HashMap<>();
        Float orderSum = orderRepository.sumPriceByEvaluateIdIn(es,null);
        Float orderSumDay = orderRepository.sumPriceByEvaluateIdIn(es, date);
        map.put("orderSum", orderSum == null ? 0 : orderSum);
        map.put("orderSumDay", orderSumDay == null ? 0 : orderSumDay);
        Float otherOrderSum = orderRepository.sumOtherPriceByEvaluateIdAndDate(es, null);
        Float otherOrderSumDay = orderRepository.sumOtherPriceByEvaluateIdAndDate(es, date);
        map.put("otherOrderSum", otherOrderSum == null ? 0 : otherOrderSum);
        map.put("otherOrderSumDay", otherOrderSumDay == null ? 0 : otherOrderSumDay);
        return ajax.setObj(map);
    }


    @RequestMapping(path = "info-export", method = RequestMethod.GET)
    public void fy_export(Long evaluateId, HttpServletResponse response) throws Exception {
    	
    	Date beginAt = (Date) session.getAttribute("beginAt");
    	Date endAt = (Date) session.getAttribute("endAt");
    	List<Order> list = orderRepository.findByEvaluateId(evaluateId,null, beginAt,endAt);
    	list.parallelStream().forEach(x ->{
    		 if(OrderState.UNPAID==x.state){
    			 x.itemPrice="0.00";
             }
    	});
        StringBuilder context = new StringBuilder("付款时间,用户,渠道,报名时间,票种,订单编号,付款状态,费用\n");
        for (Order source : list) {
            String refName = "";
    		String epName= "";
    		User user = userRepository.findOne(source.userId);
            EvaluateApply ea = evaluateApplyRepository.findByEvaluateIdAndUserId(source.itemId, source.userId);
            if(ea==null ) {
            	ea = new EvaluateApply();
            };
            if (ea.referenceId != null) {
                User refUer = userRepository.findOne(ea.referenceId);
                refName = refUer.name;
            };
            if (ea.evaluatePriceId != null) {
                EvaluatePrice ep = evaluatePriceRepository.findOne(ea.evaluatePriceId);
                epName = ep.title + "(" + ep.charge + ")";
            }
            context.append(CmnDateUtil.formatDate(source.createdAt.toString())).append(",")
            		.append(user.name+"("+user.number+")").append(",")
            		.append(refName).append(",")
            		.append(CmnDateUtil.formatDate(ea.createdAt.toString())).append(",")
                    .append(epName).append(",")
                    .append(source.id).append(",")
                    .append(source.state.desc).append(",")
                    .append(source.itemPrice).append("\n");
        }
        String nowDate = "财务管理.csv";
        String fileName = new String(nowDate.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        // 要输出的内容
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        osw.write(new String(new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        osw.write(context.toString());
        osw.flush();
    }

}
